import Axios, {
  type AxiosInstance,
  type AxiosRequestConfig,
  type CustomParamsSerializer
} from "axios";
import type {
  PureHttpError,
  RequestMethods,
  PureHttpResponse,
  PureHttpRequestConfig
} from "./types";
import { stringify } from "qs";
import NProgress from "../progress";
import { getToken, formatToken } from "@/utils/auth";
import { useUserStoreHook } from "@/store/modules/user";
import { ElMessage } from "element-plus";
import { message } from "../message";

// 相关配置请参考：www.axios-js.com/zh-cn/docs/#axios-request-config-1
const defaultConfig: AxiosRequestConfig = {
  // 请求超时时间
  timeout: 10000,
  headers: {
    Accept: "application/json, text/plain, */*",
    "Content-Type": "application/json",
    "X-Requested-With": "XMLHttpRequest"
  },
  // 数组格式参数序列化（https://github.com/axios/axios/issues/5142）
  paramsSerializer: {
    serialize: stringify as unknown as CustomParamsSerializer
  }
};

class PureHttp {
  constructor() {
    this.httpInterceptorsRequest();
    this.httpInterceptorsResponse();
  }

  /** `token`过期后，暂存待执行的请求 */
  private static requests = [];

  /** 防止重复刷新`token` */
  private static isRefreshing = false;

  /** 初始化配置对象 */
  private static initConfig: PureHttpRequestConfig = {};

  /** 保存当前`Axios`实例对象 */
  private static axiosInstance: AxiosInstance = Axios.create(defaultConfig);

  /** 重连原始请求 */
  private static retryOriginalRequest(config: PureHttpRequestConfig) {
    return new Promise(resolve => {
      PureHttp.requests.push((token: string) => {
        config.headers["Token"] = formatToken(token);
        resolve(config);
      });
    });
  }

  /** 请求拦截 */
  private httpInterceptorsRequest(): void {
    PureHttp.axiosInstance.interceptors.request.use(
      async (config: PureHttpRequestConfig): Promise<any> => {
        // 开启进度条动画
        NProgress.start();
        // 优先判断post/get等方法是否传入回调，否则执行初始化设置等回调
        if (typeof config.beforeRequestCallback === "function") {
          config.beforeRequestCallback(config);
          return config;
        }
        if (PureHttp.initConfig.beforeRequestCallback) {
          PureHttp.initConfig.beforeRequestCallback(config);
          return config;
        }
        /** 请求白名单，放置一些不需要`token`的接口（通过设置请求白名单，防止`token`过期后再请求造成的死循环问题） */
        const whiteList = ["/refresh-token", "/login"];
        return whiteList.some(url => config.url.endsWith(url))
          ? config
          : new Promise(resolve => {
              const data = getToken();
              if (data) {
                const now = new Date().getTime();
                const expired = parseInt(data.expires) - now <= 0;
                if (expired) {
                  if (!PureHttp.isRefreshing) {
                    PureHttp.isRefreshing = true;
                    // token过期刷新
                    useUserStoreHook()
                      .handRefreshToken({ refreshToken: data.refreshToken })
                      .then(res => {
                        const token = res.data.accessToken;
                        config.headers["Token"] = formatToken(token);
                        PureHttp.requests.forEach(cb => cb(token));
                        PureHttp.requests = [];
                      })
                      .finally(() => {
                        PureHttp.isRefreshing = false;
                      });
                  }
                  resolve(PureHttp.retryOriginalRequest(config));
                } else {
                  config.headers["Token"] = formatToken(data.accessToken);
                  resolve(config);
                }
              } else {
                resolve(config);
              }
            });
      },
      error => {
        return Promise.reject(error);
      }
    );
  }

  /** 响应拦截 */
  private httpInterceptorsResponse(): void {
    const instance = PureHttp.axiosInstance;
    instance.interceptors.response.use(
      (response: PureHttpResponse) => {
        // console.log("1111122222", response);
        const $config = response.config;
        NProgress.done();
        // 提取公共错误处理逻辑
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        const handleError = (message: string, errorCode: number) => {
          ElMessage.error(message);
          return Promise.reject(new Error(message));
        };

        if (typeof $config.beforeResponseCallback === "function") {
          $config.beforeResponseCallback(response);
          // console.log("44444");
          return response.data;
        }
        // console.log("22222", response);
        // 重新封装
        if (response.status !== 200) {
          // console.log("33333", response);
          // Assuming the error message is in the `msg` field of the response data
          const errorMessage = response.data.msg;
          // Display error message on the frontend
          message(errorMessage, { type: "error" });
          return Promise.reject(new Error(errorMessage));
        }

        if (
          PureHttp.initConfig.beforeResponseCallback &&
          typeof PureHttp.initConfig.beforeResponseCallback === "function"
        ) {
          PureHttp.initConfig.beforeResponseCallback(response);
          // console.log("55555");
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
          const { code, message, data } = response.data;
          switch (code) {
            case 2002:
              useUserStoreHook().logOut();
              window.location.href = "/login";
              return handleError("登录过期，请重新登录", 2002);
            case 2001:
              return handleError("登录失败", 2001);
            case 200:
              return data;
            case 401:
              useUserStoreHook().logOut();
              window.location.href = "/login";
              return handleError("未授权，请重新登录", 401);
            case 403:
              return handleError("权限不足", 403);
            case 500:
              return handleError("服务器错误", 500);
            default:
              return handleError("未知错误", code);
          }
        }
        return response.data;
      },
      (error: PureHttpError) => {
        NProgress.done();
        error.isCancelRequest = Axios.isCancel(error);

        if (error.response) {
          const status = error.response.status;
          const message =
            (error.response.data as { message?: string })?.message ||
            "请求失败";

          switch (status) {
            case 404:
              ElMessage.error("请求的资源不存在");
              break;
            case 500:
              ElMessage.error("服务器错误");
              break;
            default:
              ElMessage.error(message);
          }
        } else {
          ElMessage.error(
            (error.response?.data as { message?: string })?.message ||
              "连接错误"
          );
        }

        return Promise.reject(error);
      }
    );
  }

  /** 通用请求工具函数 */
  public request<T>(
    method: RequestMethods,
    url: string,
    param?: AxiosRequestConfig,
    axiosConfig?: PureHttpRequestConfig
  ): Promise<T> {
    const config = {
      method,
      url,
      headers: {
        ...(axiosConfig?.headers || {}),
        Token: axiosConfig?.token ? axiosConfig.token : "" // 设置请求头中的 Token 字段
      },
      ...param,
      ...axiosConfig
    } as PureHttpRequestConfig;

    // 单独处理自定义请求/响应回调
    return new Promise((resolve, reject) => {
      PureHttp.axiosInstance
        .request(config)
        .then((response: undefined) => {
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  }
  // corsor给的代码
  // public request<T>(
  //   method: RequestMethods,
  //   url: string,
  //   param?: AxiosRequestConfig,
  //   axiosConfig?: PureHttpRequestConfig
  // ): Promise<T> {
  //   // 合并配置，注意顺序以确保正确的优先级
  //   const config: PureHttpRequestConfig = {
  //     method,
  //     url,
  //     ...param,
  //     ...axiosConfig,
  //     headers: {
  //       ...param?.headers,
  //       ...axiosConfig?.headers
  //     }
  //   };
  //   console.log("fanhui", PureHttp.axiosInstance.request(config));
  //   // 直接返回 axios 请求，无需额外包装 Promise
  //   return PureHttp.axiosInstance.request(config);
  // }
  /** 单独抽离的`post`工具函数 */
  public post<T, P>(
    url: string,
    params?: AxiosRequestConfig<P>,
    config?: PureHttpRequestConfig
  ): Promise<T> {
    return this.request<T>("post", url, params, config);
  }

  /** 单独抽离的`get`工具函数 */
  public get<T, P>(
    url: string,
    params?: AxiosRequestConfig<P>,
    config?: PureHttpRequestConfig
  ): Promise<T> {
    return this.request<T>("get", url, params, config);
  }
}

export const http = new PureHttp();
